# -*- encoding: utf-8 -*-
'''
    C99 AST: This class inherits from AstToIR
    .. moduleauthor:: Juan José Fumero Alfonso <jjfumero@gmail.com>
'''
# TODO: AstToIR in Common directory

from yacf.Frontend.C99 import c99_ast

from yacf.Frontend.InternalRepr import *

class NotValidParent(Exception):
    def __init__(self, node):
        self.node = node

    def __str__(self):
        if hasattr(self, 'parent'):
            return "Node " + str(self.node) + " has an invalid parent (" + str(type(self.node.parent)) + ")"
        else:
            return "Node " + str(self.node) + " has no parent attribute (Has been decorated?)"


class C99AstToIR(AstToIR):

    def __init__(self, Writer, ast):
        """ New instance of the class
               Implements a cache to avoid recreating previous trees
        """
        super(C99AstToIR, self).__init__(Writer, ast)
        #try:
        #    current = kwargs['ast']
        #except KeyError:
        #    raise NotImplemented
        current = ast
        if not current:
            # ast must be a named parameter
            raise NotImplemented
        
        if type(current) != c_ast.FileAST:
            # FIXME: Not sure this will work properly. 
            #      When the node is new, the parent link has not been called
            #      so this may be broken...
            act_ast = current
            while act_ast != c_ast.FileAST:
                act_ast = act_ast.parent
                if act_ast == None:
                    return None
                #if act_ast == None:
                #    raise NotImplemented
            current = act_ast
        # If not already stored, create the instance
        #if not new._instanceCache.has_key(id(current)):
        #    new._instanceCache[id(current)] = super(AstToIR, new).__new__(new, *args, **kwargs)
        #    print "Cache hit " + str(id(current))
        #return  new._instanceCache[id(current)]
        ast = current

    


